package com.example.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.authority.service.RoleService;
import com.example.commons.entity.Role;
import com.example.commons.entity.UserRole;
import com.example.authority.mapper.UserRoleMapper;
import com.example.authority.service.UserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @program: authority-v3.0.7
 * @ClassName:UserRoleServiceImpl
 * @description: 用户角色表 service实现类
 * @author:dyy
 * @Version 3.0
 **/

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Resource
    private RoleService roleService;

    /**
     * 获取roleIds
     *
     * @param loginId
     * @param loginType
     * @return
     */
    @Override
    public List<Long> getRoleIds(Object loginId, String loginType) {
        // 基于id获取userolelist
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<UserRole>().in(UserRole::getUserId, loginId);

        // 基于userolelist转换成roleIds
        return this.list(userRoleLambdaQueryWrapper).stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }


    /**
     * 获取单个用户的roleIds
     *
     * @param
     * @param
     * @return
     */
    @Override
    public List<String> getRoleNameByUserId(Long userId) {
        // 查询用户关联的角色ID列表
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        List<Long> roleIds = list(queryWrapper)
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());

        if (roleIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 根据角色ID列表查询角色名称
        List<Role> roles = roleService.listByIds(roleIds);
        return roles.stream()
                .map(Role::getName)
                .collect(Collectors.toList());
    }
}
